<?php

namespace App\Models;

use App\library\mqtt\Mqtt;
use Illuminate\Database\Eloquent\Model;
use App\library\mqtt\Sammessage;

class MqttModel extends Model
{
    public $address;
    public $port;
    public $clientid;
    public $will;
    private $username;
    private $password;
    public $cafile;
    public $conn;
    public $mqtt;
    public $isNew = true;

    public function __construct()
    {
        $mqtt_config = wx_config('mqtt');
        $this->address = gethostbyname($mqtt_config['mqtt_host']);
        $this->port = $mqtt_config['mqtt_port'];
        $this->clientid = 'publish-123';
        $this->username = $mqtt_config['mqtt_user_name'];
        $this->password = $mqtt_config['mqtt_password'];
        $this->mqtt = new Mqtt();
        $this->conn = $this->mqtt->connect('mqtt', array('SAM_HOST' => $this->address, 'SAM_PORT' => $this->port));
        if (!$this->conn) {
            $arr = array('code' => 100, 'msg' => '很抱歉,MQTT服务链接失败!', 'data' => array());
            return;
        }
    }

    /**
     * sendToDevice(^-^)
     *  向设备发送MQTT指令
     * @param array $data 需要处理的参数
     * @param string $topic 主题
     * @param int $QoS
     *          0:最多一次送达,也就是发出去就fire掉,没有后面的事情了
     *          1:至少一次送达,发出去之后必须等待ack,没有ack,就要找时机重发
     *          2:准确一次送达。消息id将拥有一个简单的生命周期
     * @author Sorry
     * @date 2019-08-26 17:52
     */
    public function sendToDevice($data, $topic, $QoS = 2, $options = array())
    {
//        $msg_json = (json_encode($data);
        $msg_json = trim(str_replace("\\", '', json_encode($data)));
        return $this->sendInstruction($topic, $msg_json, $QoS);
    }

//    public function encodeData($data)
//    {
//        $head = $data['header'];
//        $dataInfo = $data['data'];
//        $CoderWrapModel = new CoderWrapModel();
//        $dataCode = $CoderWrapModel->encode($dataInfo);
//        $params = array(
//            'header' => $head,
//            'data' => $dataCode,
//        );
//        $code = json_encode($params);
//        return $code;
//    }

    /**
     * sendInstruction(^-^)
     *  发送指令
     * @param string $target 主题
     * @param json/string $msg_json 消息内容json格式
     * @param int $QoS
     *          0:最多一次送达,也就是发出去就fire掉,没有后面的事情了
     *          1:至少一次送达,发出去之后必须等待ack,没有ack,就要找时机重发
     *          2:准确一次送达。消息id将拥有一个简单的生命周期
     * @author Sorry
     * @date 2019-05-31 17:52
     */
    public function sendInstruction($target, $msg_json, $QoS = 2)
    {
        $msgCpu = new Sammessage($msg_json);
        $result = $this->mqtt->send('topic://' . $target, $msgCpu);
        if ($result) {
            $arr = array('code' => 200, 'msg' => '恭喜您,MQTT指令发送成功!', 'data' => $msg_json);
        } else {
            $arr = array('code' => 100, 'msg' => '很抱歉,MQTT指令发送失败!', 'data' => $msg_json);
        }
        return $arr;
    }
}
